package com.example.security.controller;

import com.example.security.dto.LoginDto;
import com.example.security.dto.UserAuthInfo;
import com.example.core.utils.Result;
import com.example.sys.org.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class IndexController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysUserService sysUserService;

    /****
     *
     * 用户名密码登录并返回token
     * @param loginDto
     * @return
     */
    @PostMapping(value = "login")
    public Result login(@RequestBody LoginDto loginDto) {
        Subject subject = SecurityUtils.getSubject();
        try {
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginDto.getUserName(), loginDto.getPassWord());
            subject.login(usernamePasswordToken);
            return Result.success(sysUserService.login(loginDto.getUserName()));
        } catch (Exception e) {
            logger.info(e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    /***
     * 获取当前的用户信息
     * @return
     */
    @GetMapping(value = "info")
    public Result info() {
        try {
            UserAuthInfo userInfo = sysUserService.getUserInfo();
            return Result.success(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /****
     * 注销用户，退出登录.
     * 如果返回true 表示登出成功，否则就是登出失败.
     * @return
     */
    @PostMapping(value = "logout")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return Result.success(sysUserService.logout());
    }
}
